<template>
  <div class="settings-container">
    <a-card title="账号设置" :bordered="false">
      <a-tabs v-model:activeKey="activeTab">
        <!-- 密码设置 -->
        <a-tab-pane key="password" tab="修改密码">
          <a-form
            :model="passwordForm"
            layout="vertical"
            @finish="handlePasswordChange"
          >
            <a-form-item
              label="当前密码"
              name="oldPassword"
              :rules="[{ required: true, message: '请输入当前密码' }]"
            >
              <a-input-password v-model:value="passwordForm.oldPassword" />
            </a-form-item>
            
            <a-form-item
              label="新密码"
              name="newPassword"
              :rules="[
                { required: true, message: '请输入新密码' },
                { min: 6, message: '密码至少6个字符' }
              ]"
            >
              <a-input-password v-model:value="passwordForm.newPassword" />
            </a-form-item>
            
            <a-form-item
              label="确认新密码"
              name="confirmPassword"
              :rules="[
                { required: true, message: '请确认新密码' },
                { validator: validateConfirmPassword }
              ]"
            >
              <a-input-password v-model:value="passwordForm.confirmPassword" />
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" html-type="submit" :loading="passwordLoading">修改密码</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        
        <!-- 通知设置 -->
        <a-tab-pane key="notifications" tab="通知设置">
          <a-form
            :model="notificationForm"
            layout="vertical"
            @finish="handleNotificationSettings"
          >
            <a-form-item label="电子邮件通知">
              <a-checkbox v-model:checked="notificationForm.emailNotification">
                接收电子邮件通知
              </a-checkbox>
            </a-form-item>
            
            <a-form-item label="通知类型">
              <a-checkbox-group v-model:value="notificationForm.notificationTypes">
                <a-checkbox value="comment">文章评论</a-checkbox>
                <a-checkbox value="reply">评论回复</a-checkbox>
                <a-checkbox value="like">点赞</a-checkbox>
                <a-checkbox value="system">系统通知</a-checkbox>
              </a-checkbox-group>
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" html-type="submit" :loading="notificationLoading">保存设置</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        
        <!-- 账号安全 -->
        <a-tab-pane key="security" tab="账号安全">
          <div class="security-item">
            <div class="security-info">
              <h3>账号登录</h3>
              <p>上次登录时间: {{ lastLoginTime || '未获取' }}</p>
              <p>上次登录IP: {{ lastLoginIp || '未获取' }}</p>
            </div>
          </div>
          
          <div class="security-item">
            <div class="security-info">
              <h3>账号注销</h3>
              <p class="warning-text">注意：账号注销操作不可逆，将永久删除您的所有数据。</p>
            </div>
            <a-button danger @click="showDeleteConfirm">申请注销账号</a-button>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    
    <!-- 账号注销确认对话框 -->
    <a-modal
      v-model:visible="deleteAccountVisible"
      title="账号注销确认"
      okText="确认注销"
      cancelText="取消"
      :okButtonProps="{ danger: true }"
      @ok="handleDeleteAccount"
    >
      <div class="delete-account-confirm">
        <p>请确认您是否要注销账号？此操作将：</p>
        <ul>
          <li>永久删除您的个人资料</li>
          <li>删除您发布的所有文章</li>
          <li>删除您的所有评论</li>
        </ul>
        <p>注销后，这些数据将无法恢复。</p>
        
        <a-form layout="vertical">
          <a-form-item
            label="请输入您的密码以确认"
            name="password"
            :rules="[{ required: true, message: '请输入密码确认' }]"
          >
            <a-input-password v-model:value="deleteAccountPassword" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useUserStore } from '@/stores/user';
import { 
  changePassword, 
  updateNotificationSettings, 
  getSecurityInfo, 
  deleteAccount 
} from '@/api/user';

const userStore = useUserStore();
const activeTab = ref('password');
const passwordLoading = ref(false);
const notificationLoading = ref(false);
const lastLoginTime = ref('');
const lastLoginIp = ref('');
const deleteAccountVisible = ref(false);
const deleteAccountPassword = ref('');

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 通知设置表单
const notificationForm = reactive({
  emailNotification: true,
  notificationTypes: ['comment', 'reply', 'system']
});

// 确认密码验证
const validateConfirmPassword = async (rule, value) => {
  if (value !== passwordForm.newPassword) {
    throw new Error('两次输入的密码不一致');
  }
};

// 修改密码
const handlePasswordChange = async () => {
  passwordLoading.value = true;
  try {
    await changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    });
    
    message.success('密码修改成功');
    // 清空表单
    passwordForm.oldPassword = '';
    passwordForm.newPassword = '';
    passwordForm.confirmPassword = '';
  } catch (error) {
    console.error('修改密码失败:', error);
    message.error('修改密码失败');
  } finally {
    passwordLoading.value = false;
  }
};

// 保存通知设置
const handleNotificationSettings = async () => {
  notificationLoading.value = true;
  try {
    await updateNotificationSettings({
      emailNotification: notificationForm.emailNotification,
      notificationTypes: notificationForm.notificationTypes
    });
    
    message.success('通知设置已保存');
  } catch (error) {
    console.error('保存通知设置失败:', error);
    message.error('保存通知设置失败');
  } finally {
    notificationLoading.value = false;
  }
};

// 获取安全信息
const fetchSecurityInfo = async () => {
  try {
    const data = await getSecurityInfo();
    if (data) {
      lastLoginTime.value = data.lastLoginTime || '';
      lastLoginIp.value = data.lastLoginIp || '';
    }
  } catch (error) {
    console.error('获取安全信息失败:', error);
  }
};

onMounted(() => {
  fetchSecurityInfo();
  
  // 获取用户的通知设置
  try {
    // 这里可以添加获取用户通知设置的API调用
    // const settings = await getUserNotificationSettings();
    // notificationForm.emailNotification = settings.emailNotification;
    // notificationForm.notificationTypes = settings.notificationTypes;
  } catch (error) {
    console.error('获取通知设置失败:', error);
  }
});

// 显示删除账号确认对话框
const showDeleteConfirm = () => {
  deleteAccountPassword.value = '';
  deleteAccountVisible.value = true;
};

// 处理删除账号
const handleDeleteAccount = async () => {
  if (!deleteAccountPassword.value) {
    message.error('请输入密码确认');
    return;
  }
  
  try {
    await deleteAccount({
      password: deleteAccountPassword.value
    });
    
    message.success('账号已注销');
    deleteAccountVisible.value = false;
    
    // 退出登录并清除状态
    await userStore.logout();
    // 重定向到首页
    window.location.href = '/';
  } catch (error) {
    console.error('注销账号失败:', error);
    message.error('注销账号失败，请确认密码是否正确');
  }
};
</script>

<style scoped>
.settings-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.security-item {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-info h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.security-info p {
  margin-bottom: 5px;
  color: #666;
}

.warning-text {
  color: #ff4d4f;
  font-weight: 500;
}

.delete-account-confirm ul {
  margin: 15px 0;
  padding-left: 20px;
}

.delete-account-confirm li {
  margin-bottom: 5px;
  color: #ff4d4f;
}
</style> 